package com.itheima.travel.service.impl;


import com.itheima.travel.mapper.UserMapper;
import com.itheima.travel.pojo.User;
import com.itheima.travel.pojo.UserExample;
import com.itheima.travel.req.UserVo;
import com.itheima.travel.service.UserService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;
/**
 * @author Chenglei
 * @date 2021/3/2 9:16
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    HttpSession session;


    @Override
    public Boolean registerUser(UserVo userVo) {
        User user = BeanConv.toBean(userVo, User.class);
        user.setPassword(MD5Coder.md5Encode(user.getPassword()));
        int flag = userMapper.insert(user);
        return flag>0;
    }

    @Override
    public UserVo loginUser(UserVo userVo) {
        //组装条件
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(userVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(userVo.getPassword()));
        //查询list结果集
        List<User> users = userMapper.selectByExample(example);
        //转换VO
        List<UserVo> list = BeanConv.toBeanList(users, UserVo.class);
        //判断结果
        if (list.size()==1){
            UserVo userVoResult = list.get(0);
            //放入会话
            String sessionId = session.getId();
            userVoResult.setSessionId(sessionId);
            session.setAttribute(sessionId,userVoResult);
            return userVoResult;
        }
        return null;
    }

    @Override
    public void loginOutUser() {
        //从会话中删除当前对象
        session.removeAttribute(session.getId());
    }

    @Override
    public Boolean isLogin() {
        //根据当前用户是否存在判断登录状态
        Object sessionObject = session.getAttribute(session.getId());
        return !EmptyUtil.isNullOrEmpty(sessionObject);
    }
}
